package com.iot.manager.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.material.button.MaterialButton;
import com.iot.manager.R;
import com.iot.manager.data.models.Device;
import com.iot.manager.utils.DeviceWifiManager;
import com.iot.manager.utils.UdpManager;

public class DeviceNetworkConfigActivity extends AppCompatActivity {
    private static final String EXTRA_DEVICE = "extra_device";
    private static final String EXTRA_HOTSPOT_SSID = "extra_hotspot_ssid";
    private static final String EXTRA_HOTSPOT_PASSWORD = "extra_hotspot_password";
    private static final String TAG = "DeviceNetworkConfigActivity";
    private static final int TIMEOUT = 30000; // 30秒超时

    private Toolbar toolbar;
    private ProgressBar progressBar;
    private TextView tvStatus;
    private Device device;
    private String hotspotSSID;
    private String hotspotPassword;
    private DeviceWifiManager wifiManager;
    private UdpManager udpManager;
    private Handler mainHandler;
    private boolean isConfiguring = false;

    private MaterialButton btnRetry;
    private ImageView ivStep1, ivStep2, ivStep3, ivStep4;

    private final ActivityResultLauncher<Intent> qrScannerLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                    String qrContent = result.getData().getStringExtra("qr_content");
                    if (qrContent != null && !qrContent.isEmpty()) {
                        handleQRCodeResult(qrContent);
                    } else {
                        showError("无效的二维码内容");
                    }
                }
            });

    public static void start(Context context, Device device, String hotspotSSID, String hotspotPassword) {
        Intent intent = new Intent(context, DeviceNetworkConfigActivity.class);
        intent.putExtra(EXTRA_DEVICE, device);
        intent.putExtra(EXTRA_HOTSPOT_SSID, hotspotSSID);
        intent.putExtra(EXTRA_HOTSPOT_PASSWORD, hotspotPassword);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_network_config);

        // 获取传递的数据
        device = (Device) getIntent().getSerializableExtra(EXTRA_DEVICE);
        hotspotSSID = getIntent().getStringExtra(EXTRA_HOTSPOT_SSID);
        hotspotPassword = getIntent().getStringExtra(EXTRA_HOTSPOT_PASSWORD);

        if (device == null || hotspotSSID == null || hotspotPassword == null) {
            showError("设备信息不完整");
            finish();
            return;
        }

        initViews();
        mainHandler = new Handler(Looper.getMainLooper());
        wifiManager = new DeviceWifiManager(this);
        udpManager = new UdpManager();

        // 开始配网流程
        startNetworkConfig();
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        tvStatus = findViewById(R.id.tvStatus);
        progressBar = findViewById(R.id.progressBar);
        btnRetry = findViewById(R.id.btnRetry);
        ivStep1 = findViewById(R.id.ivStep1);
        ivStep2 = findViewById(R.id.ivStep2);
        ivStep3 = findViewById(R.id.ivStep3);
        ivStep4 = findViewById(R.id.ivStep4);

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle(R.string.device_network_config);
        }

        btnRetry.setOnClickListener(v -> startNetworkConfig());
    }

    private void startQRScanner() {
        if (isConfiguring) {
            showError("配网正在进行中，请稍候...");
            return;
        }
        
        Intent intent = new Intent(this, QRScannerActivity.class);
        intent.putExtra("title", "扫描设备二维码");
        intent.putExtra("hint", "请将二维码对准扫描框");
        qrScannerLauncher.launch(intent);
    }

    private void handleQRCodeResult(String qrContent) {
        // 解析二维码内容
        try {
            // 这里可以根据实际需求解析二维码内容
            // 例如：解析设备信息、网络配置等
            updateStatus("正在处理二维码信息...");
            startNetworkConfig();
        } catch (Exception e) {
            showError("二维码内容格式错误");
        }
    }

    private void startNetworkConfig() {
        // 重置UI状态
        resetUI();
        showProgress(true);
        updateStatus("正在连接设备热点...");
        showStepWaiting(1);

        // 步骤1：连接设备热点
        wifiManager.connectToDeviceWifi(hotspotSSID, hotspotPassword, device.getDeviceId(),
                new DeviceWifiManager.ConnectionCallback() {
                    @Override
                    public void onSuccess() {
                        mainHandler.post(() -> {
                            updateStep1(true);
                            updateStatus("正在发送配置信息...");
                            showStepWaiting(2);
                            sendConfig();
                        });
                    }

                    @Override
                    public void onError(String error) {
                        mainHandler.post(() -> {
                            updateStep1(false);
                            showError("连接设备热点失败: " + error);
                        });
                    }
                });
    }

    private void sendConfig() {
        // 步骤2：发送配置信息
        String configData = String.format("%s|cfg|%d", device.getDeviceId(), System.currentTimeMillis());
        udpManager.sendConfig(configData, new UdpManager.UdpCallback() {
            @Override
            public void onSuccess() {
                mainHandler.post(() -> {
                    updateStep2(true);
                    updateStatus("等待设备响应...");
                    showStepWaiting(3);
                    waitForResponse();
                });
            }

            @Override
            public void onError(String error) {
                mainHandler.post(() -> {
                    updateStep2(false);
                    showError("发送配置失败: " + error);
                });
            }
        });
    }

    private void waitForResponse() {
        // 步骤3：等待设备响应
        updateStep3(true);
        updateStatus("配网完成");
        showStepWaiting(4);
        updateStep4(true);
        showProgress(false);
    }

    private void resetUI() {
        ivStep1.setVisibility(View.GONE);
        ivStep2.setVisibility(View.GONE);
        ivStep3.setVisibility(View.GONE);
        ivStep4.setVisibility(View.GONE);
        btnRetry.setVisibility(View.GONE);
    }

    private void updateStep1(boolean completed) {
        ivStep1.setImageResource(completed ? R.drawable.ic_success : R.drawable.ic_error);
        ivStep1.setVisibility(View.VISIBLE);
    }

    private void updateStep2(boolean completed) {
        ivStep2.setImageResource(completed ? R.drawable.ic_success : R.drawable.ic_error);
        ivStep2.setVisibility(View.VISIBLE);
    }

    private void updateStep3(boolean completed) {
        ivStep3.setImageResource(completed ? R.drawable.ic_success : R.drawable.ic_error);
        ivStep3.setVisibility(View.VISIBLE);
    }

    private void updateStep4(boolean completed) {
        ivStep4.setImageResource(completed ? R.drawable.ic_success : R.drawable.ic_error);
        ivStep4.setVisibility(View.VISIBLE);
    }

    private void showStepWaiting(int step) {
        switch (step) {
            case 1:
                ivStep1.setImageResource(R.drawable.ic_waiting);
                ivStep1.setVisibility(View.VISIBLE);
                break;
            case 2:
                ivStep2.setImageResource(R.drawable.ic_waiting);
                ivStep2.setVisibility(View.VISIBLE);
                break;
            case 3:
                ivStep3.setImageResource(R.drawable.ic_waiting);
                ivStep3.setVisibility(View.VISIBLE);
                break;
            case 4:
                ivStep4.setImageResource(R.drawable.ic_waiting);
                ivStep4.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void updateStatus(String status) {
        tvStatus.setText(status);
    }

    private void showProgress(boolean show) {
        progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    private void showError(String error) {
        Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
        updateStatus("配网失败");
        showProgress(false);
        btnRetry.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (isConfiguring) {
            showError("配网正在进行中，请稍候...");
            return;
        }
        if (wifiManager != null) {
            wifiManager.disconnect();
        }
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isConfiguring = false;
        if (mainHandler != null) {
            mainHandler.removeCallbacksAndMessages(null);
        }
        if (wifiManager != null) {
            wifiManager.disconnect();
        }
        if (udpManager != null) {
            udpManager.close();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (wifiManager != null) {
            wifiManager.disconnect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (wifiManager != null && !wifiManager.isConnected()) {
            startNetworkConfig();
        }
    }
} 